// Tetris 游戏类
class Tetris {
  constructor(page) {
    this.page = page;
    // 游戏配置
    this.cols = 10;
    this.rows = 20;
    this.blockSize = 30;
    
    // 游戏状态
    this.board = Array(this.rows).fill().map(() => Array(this.cols).fill(0));
    this.currentPiece = null;
    this.nextPiece = null;
    this.score = 0;
    this.lines = 0;
    this.level = 1;
    this.gameOver = false;
    this.paused = false;
    
    // 画布相关
    this.canvas = null;
    this.ctx = null;
    this.nextCanvas = null;
    this.nextCtx = null;
    
    // 方块颜色定义
    this.colors = [
      null,          // 0: 空
      '#FF5252',     // 1: 红色
      '#4CAF50',     // 2: 绿色
      '#2196F3',     // 3: 蓝色
      '#FFC107',     // 4: 黄色
      '#9C27B0',     // 5: 紫色
      '#00BCD4',     // 6: 青色
      '#FF9800'      // 7: 橙色
    ];
    
    // 方块形状定义
    this.shapes = [
      [],  // 空
      [[0, 0, 0, 0], [1, 1, 1, 1], [0, 0, 0, 0], [0, 0, 0, 0]],  // I
      [[2, 0, 0], [2, 2, 2], [0, 0, 0]],  // J
      [[0, 0, 3], [3, 3, 3], [0, 0, 0]],  // L
      [[4, 4], [4, 4]],  // O
      [[0, 5, 5], [5, 5, 0], [0, 0, 0]],  // S
      [[0, 6, 0], [6, 6, 6], [0, 0, 0]],  // T
      [[7, 7, 0], [0, 7, 7], [0, 0, 0]]   // Z
    ];
    
    // 游戏循环定时器
    this.gameLoopTimer = null;
    this.lastTime = 0;
    
    // 获取画布上下文
    this.initCanvas();
  }
  
  // 初始化画布
  initCanvas() {
    const query = wx.createSelectorQuery().in(this.page);
    query.select('#tetris')
      .fields({
        node: true,
        size: true
      })
      .exec((res) => {
        const canvas = res[0].node;
        const ctx = canvas.getContext('2d');
        
        // 设置canvas尺寸
        const dpr = wx.getSystemInfoSync().pixelRatio;
        canvas.width = res[0].width * dpr;
        canvas.height = res[0].height * dpr;
        ctx.scale(dpr, dpr);
        
        this.canvas = canvas;
        this.ctx = ctx;
        
        // 初始化游戏
        this.resetGame();
      });
    
    query.select('#nextPiece')
      .fields({
        node: true,
        size: true
      })
      .exec((res) => {
        const canvas = res[0].node;
        const ctx = canvas.getContext('2d');
        
        // 设置canvas尺寸
        const dpr = wx.getSystemInfoSync().pixelRatio;
        canvas.width = res[0].width * dpr;
        canvas.height = res[0].height * dpr;
        ctx.scale(dpr, dpr);
        
        this.nextCanvas = canvas;
        this.nextCtx = ctx;
      });
  }
  
  // 重置游戏
  resetGame() {
    this.board = Array(this.rows).fill().map(() => Array(this.cols).fill(0));
    this.score = 0;
    this.lines = 0;
    this.level = 1;
    this.gameOver = false;
    this.paused = false;
    
    // 更新显示
    this.updateScore();
    
    // 生成第一个方块和下一个方块
    this.currentPiece = this.createPiece();
    this.nextPiece = this.createPiece();
    
    // 隐藏游戏消息
    this.page.setData({
      showMessage: false,
      message: ''
    });
    
    // 绘制初始游戏状态
    this.drawBoard();
    this.drawNextPiece();
  }
  
  // 创建新方块
  createPiece() {
    const type = Math.floor(Math.random() * 7) + 1;
    const piece = {
      type: type,
      shape: this.shapes[type],
      x: Math.floor(this.cols / 2) - Math.floor(this.shapes[type][0].length / 2),
      y: 0
    };
    return piece;
  }
  
  // 检查碰撞
  checkCollision(piece, offsetX = 0, offsetY = 0) {
    for (let y = 0; y < piece.shape.length; y++) {
      for (let x = 0; x < piece.shape[y].length; x++) {
        if (piece.shape[y][x] !== 0) {
          const newX = piece.x + x + offsetX;
          const newY = piece.y + y + offsetY;
          
          if (
            newX < 0 || 
            newX >= this.cols || 
            newY >= this.rows || 
            (newY >= 0 && this.board[newY][newX] !== 0)
          ) {
            return true;
          }
        }
      }
    }
    return false;
  }
  
  // 旋转方块
  rotatePiece() {
    if (this.paused || this.gameOver) return;
    
    const rotatedShape = [];
    const rows = this.currentPiece.shape.length;
    const cols = this.currentPiece.shape[0].length;
    
    // 创建旋转后的形状矩阵
    for (let i = 0; i < cols; i++) {
      rotatedShape[i] = [];
      for (let j = 0; j < rows; j++) {
        rotatedShape[i][j] = this.currentPiece.shape[rows - 1 - j][i];
      }
    }
    
    const tempShape = this.currentPiece.shape;
    const originalX = this.currentPiece.x;
    const originalY = this.currentPiece.y;
    
    // 尝试标准旋转
    this.currentPiece.shape = rotatedShape;
    
    // 如果旋转后发生碰撞，尝试墙踢（wall kick）
    if (this.checkCollision(this.currentPiece)) {
      // 尝试墙踢：向左移动1格
      this.currentPiece.x--;
      if (this.checkCollision(this.currentPiece)) {
        // 向左移动不行，尝试向右移动2格（恢复原位后再向右移动1格）
        this.currentPiece.x += 2;
        if (this.checkCollision(this.currentPiece)) {
          // 向右移动不行，尝试向上移动1格
          this.currentPiece.x = originalX;
          this.currentPiece.y--;
          if (this.checkCollision(this.currentPiece)) {
            // 所有墙踢尝试都失败，恢复原状
            this.currentPiece.shape = tempShape;
            this.currentPiece.x = originalX;
            this.currentPiece.y = originalY;
          }
        }
      }
    }
    
    // 确保方块不会移动到游戏板左侧之外
    while (this.checkCollision(this.currentPiece)) {
      this.currentPiece.x++;
      if (this.currentPiece.x > this.cols) {
        // 如果无法避免碰撞，恢复原状
        this.currentPiece.shape = tempShape;
        this.currentPiece.x = originalX;
        this.currentPiece.y = originalY;
        break;
      }
    }
    
    this.drawBoard();
  }
  
  // 将当前方块固定到游戏板上
  lockPiece() {
    for (let y = 0; y < this.currentPiece.shape.length; y++) {
      for (let x = 0; x < this.currentPiece.shape[y].length; x++) {
        if (this.currentPiece.shape[y][x] !== 0) {
          const boardY = this.currentPiece.y + y;
          const boardX = this.currentPiece.x + x;
          
          // 检查游戏是否结束（方块任何部分超出游戏板顶部）
          if (boardY < 0) {
            this.gameOver = true;
            return;
          }
          
          this.board[boardY][boardX] = this.currentPiece.shape[y][x];
        }
      }
    }
    
    // 消行
    this.clearLines();
    
    // 检查是否游戏结束
    if (!this.gameOver) {
      // 使用下一个方块作为当前方块，并生成新的下一个方块
      this.currentPiece = this.nextPiece;
      this.nextPiece = this.createPiece();
      this.drawNextPiece();
      
      // 新增检查：如果新方块一出现就发生碰撞，游戏结束
      if (this.checkCollision(this.currentPiece)) {
        this.gameOver = true;
      }
    }
  }
  
  // 消行
  clearLines() {
    let linesCleared = 0;
    
    for (let y = this.rows - 1; y >= 0; y--) {
      if (this.board[y].every(cell => cell !== 0)) {
        // 移除已满的行
        this.board.splice(y, 1);
        // 在顶部添加新的空行
        this.board.unshift(Array(this.cols).fill(0));
        // 由于移除了一行，需要重新检查当前位置
        y++;
        linesCleared++;
      }
    }
    
    if (linesCleared > 0) {
      // 计算得分
      const linePoints = [0, 40, 100, 300, 1200]; // 0, 1, 2, 3, 4行的得分
      this.score += linePoints[linesCleared] * this.level;
      this.lines += linesCleared;
      
      // 检查是否升级
      this.level = Math.floor(this.lines / 10) + 1;
      
      // 更新显示
      this.updateScore();
    }
  }
  
  // 更新分数显示
  updateScore() {
    this.page.setData({
      score: this.score,
      lines: this.lines,
      level: this.level
    });
  }
  
  // 绘制游戏板
  drawBoard() {
    if (!this.ctx) return;
    
    // 清空画布
    this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);
    
    // 绘制网格背景
    this.ctx.strokeStyle = 'rgba(255, 255, 255, 0.1)';
    for (let y = 0; y < this.rows; y++) {
      for (let x = 0; x < this.cols; x++) {
        this.ctx.strokeRect(x * this.blockSize, y * this.blockSize, this.blockSize, this.blockSize);
      }
    }
    
    // 绘制游戏板上已固定的方块
    for (let y = 0; y < this.rows; y++) {
      for (let x = 0; x < this.cols; x++) {
        const cell = this.board[y][x];
        if (cell !== 0) {
          this.drawBlock(x, y, cell);
        }
      }
    }
    
    // 绘制当前方块
    if (this.currentPiece) {
      for (let y = 0; y < this.currentPiece.shape.length; y++) {
        for (let x = 0; x < this.currentPiece.shape[y].length; x++) {
          if (this.currentPiece.shape[y][x] !== 0) {
            const boardX = this.currentPiece.x + x;
            const boardY = this.currentPiece.y + y;
            if (boardY >= 0) { // 只绘制在游戏板内的部分
              this.drawBlock(boardX, boardY, this.currentPiece.shape[y][x]);
            }
          }
        }
      }
    }
    
    // 如果游戏结束，显示游戏结束消息
    if (this.gameOver) {
      this.showMessage('游戏结束！按重置键重新开始');
      this.stopGame();
    }
    
    // 如果游戏暂停，显示暂停消息
    if (this.paused) {
      this.showMessage('游戏暂停');
    }
  }
  
  // 绘制单个方块
  drawBlock(x, y, type) {
    if (!this.ctx) return;
    
    // 绘制方块主体
    this.ctx.fillStyle = this.colors[type];
    this.ctx.fillRect(x * this.blockSize, y * this.blockSize, this.blockSize, this.blockSize);
    
    // 绘制方块边框
    this.ctx.strokeStyle = 'rgba(255, 255, 255, 0.3)';
    this.ctx.lineWidth = 2;
    this.ctx.strokeRect(x * this.blockSize, y * this.blockSize, this.blockSize, this.blockSize);
    
    // 绘制方块高光效果
    this.ctx.fillStyle = 'rgba(255, 255, 255, 0.2)';
    this.ctx.fillRect(x * this.blockSize + 4, y * this.blockSize + 4, this.blockSize - 8, this.blockSize - 8);
  }
  
  // 绘制下一个方块预览
  drawNextPiece() {
    if (!this.nextCtx) return;
    
    // 清空画布
    this.nextCtx.clearRect(0, 0, this.nextCanvas.width, this.nextCanvas.height);
    
    if (this.nextPiece) {
      const nextBlockSize = 24; // 下一个方块预览的方块大小
      const centerX = (this.nextCanvas.width / wx.getSystemInfoSync().pixelRatio - this.nextPiece.shape[0].length * nextBlockSize) / 2;
      const centerY = (this.nextCanvas.height / wx.getSystemInfoSync().pixelRatio - this.nextPiece.shape.length * nextBlockSize) / 2;
      
      // 绘制下一个方块
      for (let y = 0; y < this.nextPiece.shape.length; y++) {
        for (let x = 0; x < this.nextPiece.shape[y].length; x++) {
          if (this.nextPiece.shape[y][x] !== 0) {
            const drawX = centerX + x * nextBlockSize;
            const drawY = centerY + y * nextBlockSize;
            
            // 绘制方块主体
            this.nextCtx.fillStyle = this.colors[this.nextPiece.shape[y][x]];
            this.nextCtx.fillRect(drawX, drawY, nextBlockSize, nextBlockSize);
            
            // 绘制方块边框
            this.nextCtx.strokeStyle = 'rgba(255, 255, 255, 0.3)';
            this.nextCtx.lineWidth = 2;
            this.nextCtx.strokeRect(drawX, drawY, nextBlockSize, nextBlockSize);
            
            // 绘制方块高光效果
            this.nextCtx.fillStyle = 'rgba(255, 255, 255, 0.2)';
            this.nextCtx.fillRect(drawX + 3, drawY + 3, nextBlockSize - 6, nextBlockSize - 6);
          }
        }
      }
    }
  }
  
  // 显示游戏消息
  showMessage(text) {
    this.page.setData({
      showMessage: true,
      message: text
    });
  }
  
  // 游戏主循环
  gameLoop() {
    if (!this.paused && !this.gameOver) {
      // 尝试下移方块
      if (!this.checkCollision(this.currentPiece, 0, 1)) {
        this.currentPiece.y++;
      } else {
        // 方块无法下移，固定到游戏板上
        this.lockPiece();
      }
      
      // 绘制游戏状态
      this.drawBoard();
    }
  }
  
  // 启动游戏循环
  startGame() {
    if (this.gameLoopTimer) {
      clearInterval(this.gameLoopTimer);
    }
    
    this.paused = false;
    this.page.setData({
      showMessage: false,
      message: ''
    });
    
    // 基于当前等级计算下落速度
    const dropSpeed = Math.max(50, 1000 - (this.level - 1) * 100); // 等级越高，下落越快
    
    this.gameLoopTimer = setInterval(() => {
      this.gameLoop();
    }, dropSpeed);
  }
  
  // 暂停游戏
  pauseGame() {
    this.paused = !this.paused;
    if (this.paused) {
      this.showMessage('游戏暂停');
      if (this.gameLoopTimer) {
        clearInterval(this.gameLoopTimer);
      }
    } else {
      this.page.setData({
        showMessage: false,
        message: ''
      });
      this.startGame();
    }
    this.drawBoard();
  }
  
  // 停止游戏
  stopGame() {
    if (this.gameLoopTimer) {
      clearInterval(this.gameLoopTimer);
      this.gameLoopTimer = null;
    }
  }
  
  // 获取游戏状态（用于AI决策）
  getGameState() {
    return {
      board: this.board,
      currentPiece: this.currentPiece,
      nextPiece: this.nextPiece,
      cols: this.cols,
      rows: this.rows
    };
  }
  
  // 移动方块（用于AI控制）
  movePieceLeft() {
    if (this.paused || this.gameOver) return;
    
    if (!this.checkCollision(this.currentPiece, -1, 0)) {
      this.currentPiece.x--;
      this.drawBoard();
    }
  }
  
  movePieceRight() {
    if (this.paused || this.gameOver) return;
    
    if (!this.checkCollision(this.currentPiece, 1, 0)) {
      this.currentPiece.x++;
      this.drawBoard();
    }
  }
  
  movePieceDown() {
    if (this.paused || this.gameOver) return;
    
    if (!this.checkCollision(this.currentPiece, 0, 1)) {
      this.currentPiece.y++;
      this.drawBoard();
    } else {
      this.lockPiece();
      this.drawBoard();
    }
  }
  
  hardDrop() {
    if (this.paused || this.gameOver) return;
    
    while (!this.checkCollision(this.currentPiece, 0, 1)) {
      this.currentPiece.y++;
    }
    this.lockPiece();
    this.drawBoard();
  }
}

// Tetris AI 类
class TetrisAI {
  constructor(game, page) {
    this.game = game;
    this.page = page;
    this.aiEnabled = false;
    this.aiInterval = null;
  }
  
  // 启用AI
  enableAI() {
    if (!this.aiEnabled) {
      this.aiEnabled = true;
      this.page.setData({
        aiEnabled: true
      });
      
      // 设置AI思考和执行的间隔
      this.aiInterval = setInterval(() => {
        if (!this.game.paused && !this.game.gameOver) {
          this.makeBestMove();
        }
      }, 500); // AI每500毫秒做出一次决策
    }
  }
  
  // 禁用AI
  disableAI() {
    if (this.aiEnabled) {
      this.aiEnabled = false;
      this.page.setData({
        aiEnabled: false
      });
      
      if (this.aiInterval) {
        clearInterval(this.aiInterval);
        this.aiInterval = null;
      }
    }
  }
  
  // 切换AI状态
  toggleAI() {
    if (this.aiEnabled) {
      this.disableAI();
    } else {
      this.enableAI();
    }
  }
  
  // 做出最佳移动
  makeBestMove() {
    const gameState = this.game.getGameState();
    let bestMove = null;
    let bestScore = -Infinity;
    
    console.log('==== AI开始思考最佳移动 ====');
    console.log(`当前方块类型: ${gameState.currentPiece.type}`);
    
    // 尝试所有可能的旋转
    const rotations = this.getPossibleRotations(gameState.currentPiece);
    console.log(`找到 ${rotations.length} 种可能的旋转方式`);
    
    for (const rotation of rotations) {
      // 尝试所有可能的水平位置
      const minX = 0;
      const maxX = gameState.cols - rotation.shape[0].length;
      
      for (let x = minX; x <= maxX; x++) {
        // 创建模拟的游戏板来评估这个位置
        const simulatedBoard = this.cloneBoard(gameState.board);
        const simulatedPiece = {
          ...gameState.currentPiece,
          shape: rotation.shape,
          x: x,
          y: 0
        };
        
        // 计算方块落到底部后的位置
        this.dropPieceToBottom(simulatedBoard, simulatedPiece, gameState.cols, gameState.rows);
        
        // 计算这个位置可能消除的行数（基于当前x位置）
        const clearedLines = this.calculateClearedLines(simulatedBoard, simulatedPiece);
        
        // 将方块固定到模拟的游戏板上
        this.lockPieceToBoard(simulatedBoard, simulatedPiece);
        
        // 计算这个位置的评分
        const score = this.calculateScore(simulatedBoard, gameState.cols, gameState.rows, clearedLines);
        
        console.log(`评估: 旋转 ${rotation.rotations} 次, X位置 ${x}, 预计消除行数 ${clearedLines}, 评分 ${score.toFixed(2)}`);
        
        // 更新最佳移动
        if (score > bestScore) {
          bestScore = score;
          bestMove = {
            rotation: rotation.rotations,
            x: x
          };
          console.log(`  找到更好的移动方案: 旋转 ${bestMove.rotation} 次, X位置 ${bestMove.x}, 评分 ${bestScore.toFixed(2)}`);
        }
      }
    }
    
    // 执行最佳移动
    if (bestMove) {
      console.log(`\n最终决定: 旋转 ${bestMove.rotation} 次, 移动到X位置 ${bestMove.x}`);
      this.executeMove(bestMove);
    }
    console.log('==== AI思考结束 ====\n');
  }
  
  // 执行最佳移动
  executeMove(move) {
    // 先保存当前方块的原始位置
    const originalX = this.game.currentPiece.x;
    
    console.log(`\n开始执行移动: 原始X位置 ${originalX}`);
    
    // 旋转方块到最佳角度
    if (move.rotation > 0) {
      console.log(`执行 ${move.rotation} 次旋转`);
      for (let i = 0; i < move.rotation; i++) {
        this.game.rotatePiece();
      }
    }
    
    // 旋转后，重新计算需要移动的距离
    const currentX = this.game.currentPiece.x;
    const targetX = move.x;
    const distance = targetX - currentX;
    
    console.log(`旋转后X位置 ${currentX}, 目标X位置 ${targetX}, 需要移动 ${distance > 0 ? '右' : distance < 0 ? '左' : '不移动'} ${Math.abs(distance)} 格`);
    
    // 移动方块到最佳水平位置，确保不发生碰撞
    if (distance < 0) {
      // 需要向左移动
      let moved = 0;
      for (let i = 0; i < Math.abs(distance); i++) {
        if (this.game.checkCollision(this.game.currentPiece, -1, 0)) {
          console.log(`  向左移动受阻，已移动 ${moved} 格`);
          break; // 如果会发生碰撞，停止移动
        }
        this.game.movePieceLeft();
        moved++;
      }
      console.log(`完成向左移动 ${moved} 格`);
    } else if (distance > 0) {
      // 需要向右移动
      let moved = 0;
      for (let i = 0; i < distance; i++) {
        if (this.game.checkCollision(this.game.currentPiece, 1, 0)) {
          console.log(`  向右移动受阻，已移动 ${moved} 格`);
          break; // 如果会发生碰撞，停止移动
        }
        this.game.movePieceRight();
        moved++;
      }
      console.log(`完成向右移动 ${moved} 格`);
    }
    
    // 快速下落到底部
    console.log('执行快速下落到底部');
    
    // 保存下落前的游戏板状态，用于计算实际消除的行数
    const boardBeforeDrop = this.cloneBoard(this.game.board);
    const pieceBeforeDrop = { ...this.game.currentPiece };
    
    // 执行下落
    this.game.movePieceDown();
    this.game.movePieceDown();
    
    // 计算实际消除的行数
    const actualClearedLines = this.calculateClearedLines(boardBeforeDrop, pieceBeforeDrop);
    console.log(`移动后实际消除行数: ${actualClearedLines}`);
  }
  
  // 获取方块的所有可能旋转
  getPossibleRotations(piece) {
    const rotations = [];
    const originalShape = piece.shape;
    let currentShape = originalShape;
    
    // 尝试最多4种旋转（有些方块旋转4次后会回到原始形状）
    for (let i = 0; i < 4; i++) {
      // 检查这个旋转是否已经存在（避免重复）
      let exists = false;
      for (const existing of rotations) {
        if (this.shapesEqual(currentShape, existing.shape)) {
          exists = true;
          break;
        }
      }
      
      if (!exists) {
        // 创建模拟的游戏板和方块来检查消除行数
        const simulatedBoard = this.cloneBoard(this.game.board);
        const simulatedPiece = {
          ...piece,
          shape: currentShape,
          x: piece.x,
          y: piece.y
        };
        
        // 计算方块落到底部后的位置
        this.dropPieceToBottom(simulatedBoard, simulatedPiece, this.game.cols, this.game.rows);
        
        // 计算这个旋转可能消除的行数
        const clearedLines = this.calculateClearedLines(simulatedBoard, simulatedPiece);
        
        rotations.push({
          shape: currentShape,
          rotations: i,
          clearedLines: clearedLines
        });
      }
      
      // 旋转方块
      currentShape = this.rotateShape(currentShape);
    }
    
    return rotations;
  }
  
  // 旋转形状矩阵
  rotateShape(shape) {
    const rows = shape.length;
    const cols = shape[0].length;
    const rotated = [];
    
    for (let i = 0; i < cols; i++) {
      rotated[i] = [];
      for (let j = 0; j < rows; j++) {
        rotated[i][j] = shape[rows - 1 - j][i];
      }
    }
    
    return rotated;
  }
  
  // 检查两个形状是否相同
  shapesEqual(shape1, shape2) {
    if (shape1.length !== shape2.length) return false;
    
    for (let y = 0; y < shape1.length; y++) {
      if (shape1[y].length !== shape2[y].length) return false;
      
      for (let x = 0; x < shape1[y].length; x++) {
        if (shape1[y][x] !== shape2[y][x]) return false;
      }
    }
    
    return true;
  }
  
  // 克隆游戏板
  cloneBoard(board) {
    return board.map(row => [...row]);
  }
  
  // 将方块落到模拟游戏板的底部
  dropPieceToBottom(board, piece, cols, rows) {
    while (!this.checkCollision(board, piece, 0, 1, cols, rows)) {
      piece.y++;
    }
  }
  
  // 检查碰撞
  checkCollision(board, piece, offsetX = 0, offsetY = 0, cols, rows) {
    for (let y = 0; y < piece.shape.length; y++) {
      for (let x = 0; x < piece.shape[y].length; x++) {
        if (piece.shape[y][x] !== 0) {
          const newX = piece.x + x + offsetX;
          const newY = piece.y + y + offsetY;
          
          if (
            newX < 0 || 
            newX >= cols || 
            newY >= rows || 
            (newY >= 0 && board[newY][newX] !== 0)
          ) {
            return true;
          }
        }
      }
    }
    return false;
  }
  
  // 将方块固定到模拟的游戏板上
  lockPieceToBoard(board, piece) {
    for (let y = 0; y < piece.shape.length; y++) {
      for (let x = 0; x < piece.shape[y].length; x++) {
        if (piece.shape[y][x] !== 0) {
          const boardY = piece.y + y;
          const boardX = piece.x + x;
          
          if (boardY >= 0 && boardY < board.length && boardX >= 0 && boardX < board[0].length) {
            board[boardY][boardX] = piece.shape[y][x];
          }
        }
      }
    }
  }
  
  // 计算消除的行数
  calculateClearedLines(board, piece) {
    let clearedLines = 0;
    // 克隆当前游戏板，避免修改原始游戏板
    const tempBoard = this.cloneBoard(board);
    // 将当前方块固定到克隆的游戏板上
    this.lockPieceToBoard(tempBoard, piece);
    
    // 遍历克隆游戏板的每一行
    for (let y = 0; y < tempBoard.length; y++) {
      // 检查当前行是否所有单元格都不为0
      if (tempBoard[y].every(cell => cell !== 0)) {
        // 如果是，则该行可以消除，消除行数加1
        clearedLines++;
      }
    }
    
    return clearedLines;
  }
  
  // 计算底部紧凑度（不给下方留下空格，越高越好）
  calculateBottomCompactness(board, cols, rows) {
    let compactness = 0;
    
    for (let x = 0; x < cols; x++) {
      let bottomEmptyRows = 0;
      let foundBlock = false;
      
      // 从底部向上检查，计算底部连续的空行数
      for (let y = rows - 1; y >= 0; y--) {
        if (board[y][x] !== 0) {
          foundBlock = true;
          break;
        } else {
          bottomEmptyRows++;
        }
      }
      
      // 如果这一列有方块，且底部没有空格，得分最高
      if (foundBlock && bottomEmptyRows === 0) {
        compactness += 1;
      }
      // 如果有少量底部空格，得分中等
      else if (foundBlock && bottomEmptyRows <= 2) {
        compactness += 0.5;
      }
      // 如果底部空格太多，得分较低
      else if (foundBlock) {
        compactness += 0.1;
      }
    }
    
    return compactness;
  }
  
  // 计算方块平滑度（确保新方块本身不给后面的方块留下空格，越高越好）
  calculateBlockSmoothness(board, cols, rows) {
    let smoothness = 0;
    
    // 检查每一行的方块分布是否平滑，避免在方块上方或中间留下不规则空格
    for (let y = 0; y < rows; y++) {
      let leftmostBlock = cols;
      let rightmostBlock = -1;
      let blockCount = 0;
      
      // 找出这一行中最左边和最右边的方块位置
      for (let x = 0; x < cols; x++) {
        if (board[y][x] !== 0) {
          leftmostBlock = Math.min(leftmostBlock, x);
          rightmostBlock = Math.max(rightmostBlock, x);
          blockCount++;
        }
      }
      
      // 如果这一行有方块
      if (blockCount > 0) {
        // 计算这一行中实际填充的方块数与理想连续方块数的比率
        const expectedBlocks = rightmostBlock - leftmostBlock + 1;
        const rowSmoothness = blockCount / expectedBlocks;
        smoothness += rowSmoothness;
        
        // 特别奖励完全连续的行
        if (rowSmoothness === 1) {
          smoothness += 0.5;
        }
      }
    }
    
    // 检查列之间的高度差异，避免形成锯齿状的顶部
    const heights = this.calculateHeights(board, cols, rows);
    for (let x = 1; x < cols; x++) {
      const heightDiff = Math.abs(heights[x] - heights[x - 1]);
      // 高度差异越小，平滑度越高
      smoothness += (4 - Math.min(heightDiff, 4)) * 0.2;
    }
    
    return smoothness;
  }
  
  // 计算位置评分
  calculateScore(board, cols, rows, clearedLines) {
    let score = 0;
    
    // 计算堆积高度（越低越好）
    const heights = this.calculateHeights(board, cols, rows);
    const avgHeight = heights.reduce((a, b) => a + b, 0) / heights.length;
    const maxHeight = Math.max(...heights);
    
    // 计算行的完整度（越高越好）
    const rowCompleteness = this.calculateRowCompleteness(board, cols, rows);
    
    console.log(`heights:${heights}`);
    // 计算空洞数量（越少越好）
    const holes = this.calculateHoles(board, cols, rows, heights);
    
    // 计算粗糙度（相邻列高度差的总和，越小越好）
    const roughness = this.calculateRoughness(heights);
    
    // 计算行转换次数（方块堆叠的水平变化次数，越少越好）
    const rowTransitions = this.calculateRowTransitions(board, cols, rows);
    
    // 计算底部紧凑度（不给下方留下空格，越高越好）
    const bottomCompactness = this.calculateBottomCompactness(board, cols, rows);
    
    // 计算方块平滑度（新方块本身不给后面的方块留下空格，越高越好）
    const blockSmoothness = this.calculateBlockSmoothness(board, cols, rows);
    
    // 评分公式（权重可以调整）
    score += clearedLines * 10;     // 消除行数（权重大幅增加）
    score += bottomCompactness * 8; // 底部紧凑度（权重仅次于消行）
    score += blockSmoothness * 0;  // 方块平滑度（权重较高，确保新方块不给后面留下空格）
    score -= ( maxHeight - avgHeight) * 20;          // 平均高度（权重增加）
    // score -= maxHeight * 8;          // 最大高度（权重增加）
    score += rowCompleteness * 2;     // 行的完整度
    score -= holes * 6;             // 空洞数量（权重增加）
    score -= roughness * 2;           // 粗糙度
    score -= rowTransitions * 1;      // 行转换次数
    // score -= holes * 100;             // 空洞数量（权重增加）
    console.log(`clearedLines:${clearedLines} ,底部紧凑度 bottomCompactness:${bottomCompactness},方块平滑度 blockSmoothness:${blockSmoothness}, 平均高度 avgHeight:${avgHeight} 最大高度 maxHeight:${maxHeight} 行的完整度 rowCompleteness:${rowCompleteness} 粗糙度:${roughness} 行转换次数:${rowTransitions} 空洞数量:${holes} `);    
    return score;
  }
  
  // 计算每列的高度
  calculateHeights(board, cols, rows) {
    const heights = [];
    
    for (let x = 0; x < cols; x++) {
      let height = 0;
      // 从顶部到底部检查，计算实际高度（有方块的行数）
      for (let y = 0; y < rows; y++) {
        if (board[y][x] !== 0) {
          // 高度是从底部到第一个方块的距离
          height = rows - y;
          break;
        }
      }
      heights.push(height);
    }
    
    return heights;
  }
  
  // 计算行的完整度
  calculateRowCompleteness(board, cols, rows) {
    let completeness = 0;
    
    for (let y = 0; y < rows; y++) {
      const filledCells = board[y].filter(cell => cell !== 0).length;
      completeness += filledCells / cols;
    }
    
    return completeness;
  }
  
  // 计算空洞数量
  calculateHoles(board, cols, rows, heights) {
    let holes = 0;
    
    for (let x = 0; x < cols; x++) {
      // 从底部开始，计算到有方块的位置
      const height = heights[x];
      const startY = rows - height;
      
      for (let y = rows - 1; y >= startY; y--) {
        if (board[y][x] === 0) {
          holes++;
        }
      }
    }
    
    return holes;
  }
  
  // 计算粗糙度
  calculateRoughness(heights) {
    let roughness = 0;
    
    for (let i = 1; i < heights.length; i++) {
      roughness += Math.abs(heights[i] - heights[i - 1]);
    }
    
    return roughness;
  }
  
  // 计算行转换次数
  calculateRowTransitions(board, cols, rows) {
    let transitions = 0;
    
    for (let y = 0; y < rows; y++) {
      let prevCell = board[y][0] !== 0;
      for (let x = 1; x < cols; x++) {
        const currentCell = board[y][x] !== 0;
        if (currentCell !== prevCell) {
          transitions++;
          prevCell = currentCell;
        }
      }
    }
    
    return transitions;
  }
}

// 页面逻辑
Page({
  data: {
    score: 0,
    lines: 0,
    level: 1,
    aiEnabled: false,
    showMessage: false,
    message: ''
  },
  
  onLoad: function() {
    // 页面加载时初始化游戏
    setTimeout(() => {
      this.initGame();
    }, 100);
  },
  
  onUnload: function() {
    // 页面卸载时清理资源
    if (this.tetris) {
      this.tetris.stopGame();
    }
    if (this.tetrisAI) {
      this.tetrisAI.disableAI();
    }
  },
  
  // 初始化游戏
  initGame: function() {
    this.tetris = new Tetris(this);
    this.tetrisAI = new TetrisAI(this.tetris, this);
  },
  
  // 开始游戏
  startGame: function() {
    if (this.tetris) {
      this.tetris.startGame();
    }
  },
  
  // 暂停游戏
  pauseGame: function() {
    if (this.tetris) {
      this.tetris.pauseGame();
    }
  },
  
  // 重置游戏
  resetGame: function() {
    if (this.tetris) {
      this.tetris.resetGame();
    }
    if (this.tetrisAI) {
      this.tetrisAI.disableAI();
    }
  },
  
  // 切换AI
  toggleAI: function() {
    if (this.tetrisAI) {
      this.tetrisAI.toggleAI();
    }
  },
  
  // 移动方块
  moveLeft: function() {
    if (this.tetris) {
      this.tetris.movePieceLeft();
    }
  },
  
  moveRight: function() {
    if (this.tetris) {
      this.tetris.movePieceRight();
    }
  },
  
  moveDown: function() {
    if (this.tetris) {
      this.tetris.movePieceDown();
    }
  },
  
  moveUp: function() {
    // 上键在移动端可以作为旋转功能
    this.rotatePiece();
  },
  
  // 旋转方块
  rotatePiece: function() {
    if (this.tetris) {
      this.tetris.rotatePiece();
    }
  },
  
  // 快速下落
  hardDrop: function() {
    if (this.tetris) {
      this.tetris.hardDrop();
    }
  }
})